package com.flw.dao.impl;

import com.flw.dao.ICinemaDao;
import com.flw.entity.Address;
import com.flw.entity.Cinema;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 本类用于:
 *
 * @author Bruce
 * @create 2017-07-20 15:41
 **/
@SuppressWarnings("all")
@Repository
@Transactional
public class CinemaDaoImpl implements ICinemaDao {

    @Autowired
    private SessionFactory sessionFactory;

    public Session getSession(){
        return sessionFactory.getCurrentSession();
    }

    @Override
    public Cinema findById(Long id) {
        return (Cinema) getSession().get(Cinema.class,id);
    }

    @Override
    public void save(Cinema cinema) {
        getSession().save(cinema);
    }

    @Override
    public void delete(Cinema cinema) {
        getSession().delete(cinema);
    }

    @Override
    public void update(Cinema cinema) {
        Cinema ci = (Cinema) getSession().get(Cinema.class, cinema.getId());
        if(ci != null){
            getSession().clear();
            getSession().update(cinema);
        }
    }


    //TODO 这里不知道QBC查询是不是正确
    @Override
    public List<Cinema> findByAddress(Address address) {
        Criteria c = getSession().createCriteria(Cinema.class,"ci");
        c.add(Restrictions.like("cmAddress","%"+address+"%"));
        return c.list();
    }

    @Override
    public Long getRowCount(String cmName) {
        Criteria c = getSession().createCriteria(Cinema.class,"cm");
        if(cmName != null){
            c.add(Restrictions.like("cmName",cmName));
        }
        return (Long) c.setProjection(Projections.rowCount()).uniqueResult();
    }

    @Override
    public List<Cinema> findByConditions(String cmName, Long pageNow, Long pageSize) {
        Criteria c = getSession().createCriteria(Cinema.class,"cm");
        if(cmName != null){
            c.add(Restrictions.like("cmName",cmName));
        }
        c.setFirstResult((int) ((pageNow-1)*pageSize)).setMaxResults(pageSize.intValue());

        return c.list();
    }
}
